//
// HostApi.cpp for HostApi in /home/mambou_j//babel-2014/babel-2014/Portaudio
// 
// Made by jacquesquentin mamboumouafo
// Login   <mambou_j@epitech.net>
// 
// Started on  Tue May 15 19:11:49 2012 jacquesquentin mamboumouafo
// Last update Tue May 15 19:58:47 2012 jacquesquentin mamboumouafo
//


#include	"HostApi.hpp"
#include	"System.hpp"
#include	"Device.hpp"
#include	"SystemDeviceIterator.hpp"
#include	"Exception.hpp"

namespace	portaudio
{

  HostApi::HostApi(PaHostApiIndex index) : devices_(NULL)
  {
	try
	  {
	    info_ = PaGetHostApiInfo(index);

	    int	numDevices = deviceCount();

	    devices_ new Device*[numDevices];

	    for (int i = 0; i < numDevices; i++)
	      {
		PaDeviceIndex deviceIndex = Pa_HostApiDeviceIndexToDeviceIndex(index, i);
		if (deviceIndex < 0)
		  {
		    throw PaException(deviceIndex);
		  }

		devices_[i] = &System::instance().deviceByIndex(deviceIndex);
	      }
	  }
	catch (const std::exception &e)
	  {
	    delete[] devices_;
	    throw e;
	  }
  }

  HostApi::~HostApi()
  {
    delete[] devices_;
  }

  PaHostApiTypeId	HostApi::indexId() const
  {
    return info_->type;
  }

  PaHostApiIndex	HostApi::index() const
  {
    PaHostApiIndex index = Pa_HostApiTypeIdToHostApiIndex(typeId());

    if (index < 0)
      throw PaException(index);

    return index;
  }

  const	char *HostApi::name() const
  {
    return info_->name;
  }

  int	HostApi::deviceCount() const
  {
    return info_->deviceCount;
  }

  HostApi::DeviceIterator HostApi::devicesBegin()
  {
    DeviceIterator	tmp;
    tmp.ptr_ = &devices_[0];
    return tmp;
  }

  HostApi::DeviceIterator HostApi::devicesEnd()
  {
    DeviceIterator	tmp;
    tmp.ptr_ = &devices_[deviceCount()];
    return tmp;
  }

  Device	&HostApi::defaultInputDevice() const
  {
    return System::instance().deviceByIndex(info_->defaultInputDevice);
  }

  Device	&HostApi::defaultOutputDevice() const
  {
    return System::instance().deviceByIndex(info_->defaultOutputDevice);
  }

  bool	HostApi::operator==(const HostApi &rhs) const
  {
    return (typeId() == rhs.typeId());
  }

  bool	HostApi::operator!=(const HostApi &rhs) const
  {
    return !(*this == rhs);
  }
}
